package a07_二叉树;

/**
 * <p>
 * a32_将有序数组转换为二叉搜索树复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/4/25
 */
public class a32_将有序数组转换为二叉搜索树复习2 {
    public TreeNode sortedArrayToBST(int[] nums) {
        return traversal(nums, 0, nums.length - 1);
    }

    public TreeNode traversal(int[] nums,int leftIdx,int rightIdx) {
        if(leftIdx > rightIdx){
            return null;
        }else if(leftIdx == rightIdx){
            return new TreeNode(nums[leftIdx]);
        }

        int middleIdx = leftIdx + (rightIdx - leftIdx)/2;
        TreeNode root = new TreeNode(nums[middleIdx]);
        root.left = traversal(nums,leftIdx,middleIdx - 1);
        root.right = traversal(nums,middleIdx + 1,rightIdx);
        return root;
    }
}
